package com.meizi.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.meizi.mall.common.to.es.SkuEsModel;
import com.meizi.mall.search.config.ElasticsearchConfig;
import com.meizi.mall.search.constant.EsConstant;
import com.meizi.mall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.io.IOException;
import java.util.List;

/**
 * @author meizi
 * @email enjoymeizi@gmail.com
 * @date 2021/1/20 16:25
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient esClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> listSkuModel) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : listSkuModel) {
            // 1、构造请求 指定es索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 1.1 指定id
            indexRequest.id(model.getSkuId().toString());
            // 1.2 将对象esmodel对象转换成 json 进行存储
            String s = JSON.toJSONString(model);
            // 1.3 设置文档源
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = esClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
        log.info("产品上架保存es数据返回：{}",bulk);
        boolean b = bulk.hasFailures();
        return b;
    }
}
